package org.answer.controller;



import org.answer.constant.MessageConstant;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.entity.Result;
import org.answer.pojo.CheckItem;
import org.answer.service.BehaviorLogService;
import org.answer.service.CheckItemService;
import org.answer.utils.BehaviorLogUtils;
import org.answer.utils.GetUserNameUtils;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 检查项管理
 */

@RestController
@RequestMapping("/checkitem")
public class CheckItemController {

        @Reference//查找服务
        private CheckItemService checkItemService;

    @Reference
    private BehaviorLogService behaviorLogService;
    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();

    //  新增检查项
    @PreAuthorize("hasAuthority('CHECKITEM_ADD')")  //权限校验
    @RequestMapping("/add")
    //@RequestBody解析提交过来的json数据 ，封装成CheckItem
    public Result add(@RequestBody CheckItem checkItem, HttpServletRequest request){
        List<CheckItem> list = checkItemService.findAll();
        try{
            for (CheckItem item : list) {
                if (item.getCode().equals(checkItem.getCode())){
                    return new Result(false, "当前项目编码已占用，请输入其他编码！");
                }
            }
            checkItemService.add(checkItem);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ADD_CHECKITEM_SUCCESS
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ADD_CHECKITEM_FAIL
                    )
            );
            //服务调用失败
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }


    //检查项分页查询
    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")    //权限校验
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = checkItemService.pageQuery(queryPageBean);
        return pageResult;
    }



    //编辑检查项
    @PreAuthorize("hasAuthority('CHECKITEM_EDIT')") //  权限校验
    @RequestMapping("/edit")
    public Result edit(@RequestBody CheckItem checkItem,HttpServletRequest request){
        List<CheckItem> list = checkItemService.findAll();
        Integer id = checkItem.getId();
        String oldCode = checkItemService.findById(id).getCode();

        try{
            if(checkItem.getCode().equals(oldCode)){

                checkItemService.edit(checkItem);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_CHECKITEM_SUCCESS
                        )
                );
            }else {
                for (CheckItem item : list) {
                    if (item.getCode().equals(checkItem.getCode())){
                        return new Result(false, "当前项目编码已占用，请输入其他编码！");
                    }
                }
                checkItemService.edit(checkItem);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_CHECKITEM_SUCCESS
                        )
                );
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.EDIT_CHECKITEM_FAIL
                    )
            );
            //服务调用失败
            return new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            CheckItem checkItem = checkItemService.findById(id);
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, checkItem);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            //服务调用失败
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
        }
    }


    //删除检查项
    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")
    @RequestMapping("/delete")
    public Result delete(Integer id, HttpServletRequest request) {
        try {
            checkItemService.deleteById(id);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_CHECKITEM_SUCCESS
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_CHECKITEM_FAIL
                    )
            );
            //服务调用失败
            return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<CheckItem> list = checkItemService.findAll();
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            //服务调用失败
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
        }
    }


}
